package servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import session.CommentDao;
import utility.ReplaceString;
import entity.Comment;
import entity.User;

/**
 * Kontroler koji omogućava menjanje komentara
 * 
 * @author jung & rigo
 *
 */
public class ChangeComment extends HttpServlet{
	private static final long serialVersionUID = -8433464695529472168L;
	
	final int MAX_SPACES = 10;
	
	@EJB
	protected CommentDao commentDao;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			User user = (User)request.getSession().getAttribute("user");
			if(user==null) {
				getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
				return;
			}
			String commentId=request.getParameter("commentId");
			String comment = request.getParameter("comment");
			if(commentId==null) {
				getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
				return;
			}
			//request.setAttribute("comment", commentDao.findById(Integer.parseInt(commentId)));
			Comment c = commentDao.findById(Integer.parseInt(commentId));
			if (c==null) {
				getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
				return;
			}
			if(comment==null || "".equalsIgnoreCase(comment.trim())) {
				getServletContext().getRequestDispatcher("/PrepareAppointmentView?appId="+c.getAppointment().getAppointmentId()).forward(request, response);
				return;
			}
			c.setDateChanged(new Date());
			c.setUserChanged(user);
			c.setText(ReplaceString.splitString(comment));
			commentDao.merge(c);
			getServletContext().getRequestDispatcher("/PrepareAppointmentView?appId="+c.getAppointment().getAppointmentId()).forward(request, response);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
